package com.wr.springbootsss.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 王瑞
 * @description:  自定义拦截器类
 * @date 2020/3/11  15:03
 */
@Component
public class MyInterceptor implements HandlerInterceptor {


    //登录拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        //在session中查询用户 若为空 则重定向到登录页面
        if (user==null){
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/login/toLogin");
            return false;
        }else {
            return true;

        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
